import React, { useCallback, useEffect, useState } from 'react';
import { Drawer, Button, message, Upload } from 'antd';
import { ProForm, ProFormText, ProFormDigit } from '@ant-design/pro-components';
import { UploadOutlined } from '@ant-design/icons';
import { useRequest } from '@umijs/max';
import { createProduct, updateProduct } from '@/services/ant-design-pro/product';
import { upload } from '@/services/ant-design-pro/api';

const FormDrawer: React.FC<{
    visible: boolean;
    onClose: () => void;
    currentRow: any;
    onFinish: () => void;
    productId: string; // Add productId prop
    type: string; // Add type prop
    attributeUrl: string;
    setImageUrl: (url: string | undefined) => void;
}> = ({ visible, onClose, currentRow, onFinish, form, productId, type, attributeUrl, setImageUrl }) => {
    const [fileList, setFileList] = useState<any[]>([]);
    useEffect(() => {
        if (attributeUrl) {
            setFileList([{ url: attributeUrl }]);
        }
    }, [attributeUrl]);

    const { run: submitProduct, loading } = useRequest(
        currentRow ? updateProduct : createProduct,
        {
            manual: true,
            onSuccess: () => {
                message.success('操作成功');
                onClose();
                onFinish();
            },
            onError: () => {
                message.error('操作失败');
            },
        }
    );

    const handleFinish = useCallback(
        async (values: any) => {
            console.log(productId, type, '--------')
            console.log(values)
            await submitProduct({ ...values, productId: productId, type });
        },
        [submitProduct, productId, type]
    );

    const handleUpload = async (file: File) => {
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await upload(formData);
            console.log(response)
            setImageUrl(response.data[0]);
            setFileList([{ url: response.data[0] }]);
            form.setFieldsValue({ attributeUrl: response.data[0] });
        } catch (error) {
            message.error('上传图片失败，请重试');
        }
    };

    return (
        <Drawer
            width={600}
            open={visible}
            onClose={onClose}
            title={currentRow ? '编辑解决方案' : '创建解决方案'}
        >
            <ProForm
                form={form}
                initialValues={currentRow}
                onFinish={(params) => handleFinish({ ...currentRow, ...params })}
                layout="vertical"
                submitter={{
                    render: (props, dom) => {
                        return [
                            <Button
                                key="submit"
                                type="primary"
                                onClick={() => props.submit()}
                            >
                                提交
                            </Button>,
                        ];
                    },
                }}
            >
                { type === '1' && (
                    <>
                    <ProFormText
                    name="attributeTitle"
                    label="属性标题"
                    placeholder="请输入属性标题"
                    rules={[{ required: true, message: '属性名称是必填项' }]}
                />
                    </>
                    
                ) }
                { type === '2' && (
                    <>
                    <ProFormText
                    name="attributeTitle"
                    label="属性标题"
                    placeholder="请输入属性标题"
                    rules={[{ required: true, message: '属性名称是必填项' }]}
                />
                 <ProFormText
                    name="attributeSubtitle"
                    label="属性副标题"
                    placeholder="请输入属性副标题"
                />
                  <ProFormText
                    name="typeTitle"
                    label="导航名称"
                    placeholder="请输入导航名称"
                />
                    </>
                    
                ) }
                
                <ProFormDigit
                    name="sort"
                    label="排序"
                    placeholder="请输入排序"
                />
                <ProFormDigit
                    name="attributeUrl"
                    label="图片"
                >
                    <Upload
                        listType="picture-card"
                        showUploadList={false}
                        fileList={fileList}
                        customRequest={({ file }) => handleUpload(file as File)}
                    >
                        {attributeUrl ? (
                            <img src={attributeUrl} alt="图片" style={{ width: '100%' }} />
                        ) : (
                            <div>
                                <UploadOutlined />
                                <div style={{ marginTop: 8 }}>上传图片</div>
                            </div>
                        )}
                    </Upload>
                </ProFormDigit>
            </ProForm>
        </Drawer>
    );
};

export default FormDrawer;